package com.meihua.baoleyi.fragment;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.meihua.baoleyi.R;
import com.meihua.baoleyi.base.BaseFragment;
import com.meihua.baoleyi.bean.MeInfoBean;
import com.meihua.baoleyi.common.APIServer;
import com.meihua.baoleyi.common.MyApp;
import com.meihua.baoleyi.common.PrefsHelper;
import com.meihua.baoleyi.dialog.ReleasePhotoDialog;
import com.meihua.baoleyi.model.LoginInfo;
import com.meihua.baoleyi.net.NetHelper;
import com.meihua.baoleyi.ui.AddressActivity;
import com.meihua.baoleyi.ui.MemberDetailActivity;
import com.meihua.baoleyi.ui.MessageActivity;
import com.meihua.baoleyi.ui.MyCertificationActivity;
import com.meihua.baoleyi.ui.MyOrderActivity;
import com.meihua.baoleyi.ui.MyWalletActivity;
import com.meihua.baoleyi.ui.PersonalProfileActivity;
import com.meihua.baoleyi.ui.SettingActivity;
import com.meihua.baoleyi.utils.CircularImage;
import com.meihua.baoleyi.utils.ToastUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.TreeMap;

import okhttp3.Call;
import okhttp3.Response;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * Created by liming on 2017/10/16
 * 我的模块
 */

public class WoDeFragment extends BaseFragment implements View.OnClickListener {
    private static final String ACTION_NAME = "PayDialog";
    private Context mcontext;
    private ImageView mIv_setting;//设置
    private ImageView mIv_message;//消息
    private RelativeLayout mRl_personal_profil;//个人资料
    private RelativeLayout mRl_my_certification;//我的认证
    private RelativeLayout mRl_my_order;//我的订单
    private RelativeLayout mRl_my_wallet;//我的钱包
    private RelativeLayout mRl_address;//地址管理
    private CircularImage mAvatar;//头像
    private TextView mName;//姓名
    private TextView hysj;
    private TextView maid; //身份证认证状态
    private MeInfoBean meInfoBean;
    private View view;
    private MemberBroadcastReceiver mBroadcastReceiver;
    private boolean certificate;
    private ImageView ivVip;
    private int level;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mcontext = activity;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.wode_fragment, container, false);
        initView(view);
        //注册广播
        registerBroadcastReceiver();
        return view;
    }

    /**
     * 初始化View
     * @param view
     */
    private void initView(View view) {
        mIv_setting = (ImageView) view.findViewById(R.id.iv_shezhi);
        mIv_message = (ImageView) view.findViewById(R.id.iv_message);
        mRl_personal_profil = (RelativeLayout) view.findViewById(R.id.rl_ziliao);
        mRl_my_certification = (RelativeLayout) view.findViewById(R.id.rl_renzheng);
        mRl_my_order = (RelativeLayout) view.findViewById(R.id.rl_detail);
        mRl_my_wallet = (RelativeLayout) view.findViewById(R.id.rl_money);
        mRl_address = (RelativeLayout) view.findViewById(R.id.rl_address);

        mAvatar = (CircularImage) view.findViewById(R.id.iv_avatar);
        mName = (TextView) view.findViewById(R.id.tv_name);
        hysj = (TextView) view.findViewById(R.id.tv_hysj);
        maid = (TextView) view.findViewById(R.id.tv_maid);
        ivVip = (ImageView)view.findViewById(R.id.ivVip);

        mIv_setting.setOnClickListener(this);
        mIv_message.setOnClickListener(this);
        mRl_personal_profil.setOnClickListener(this);
        mRl_my_certification.setOnClickListener(this);
        mRl_my_order.setOnClickListener(this);
        mRl_my_wallet.setOnClickListener(this);
        mRl_address.setOnClickListener(this);
        mAvatar.setOnClickListener(this);
        hysj.setOnClickListener(this);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        getServiceData();
    }

    /**
     * 获取服务器数据
     */
    private void getServiceData() {
        TreeMap<String, String> treeMap = new TreeMap<String, String>() {
            {
                put("id", MyApp.getInstance().getUser_id());//用户id
            }
        };
        NetHelper.get(APIServer.AVATAR_URL, treeMap, true, new NetHelper.HttpCallBack() {

            @Override
            public void onSuccess(String s, Call call, Response response) {
                /*请求得到的数据*/
                meInfoBean = NetHelper.getBeanForJson(MeInfoBean.class, s);
                if (meInfoBean == null) return;
                if (meInfoBean.getCode() == 200) {
                    MyApp.getInstance().setAvatar(meInfoBean.getData().getAvatar());
                    try {
                        Glide.with(getActivity()).load(meInfoBean.getData().getAvatar()).placeholder(R.mipmap.chanpin).into(mAvatar);
                    } catch (Exception e) {
                        e.printStackTrace();

                    }
                    mName.setText(meInfoBean.getData().getUname());
                    //0=>普通用户 1=>中级编外导购 2=>高级编外导购 3=>合伙人
                    level = meInfoBean.getData().getLevel();
                    if(level == 0) {
                        hysj.setText("普通用户");
                        ivVip.setVisibility(View.GONE);
                    }else if(level ==1 ){
                        ivVip.setVisibility(View.VISIBLE);
                        ivVip.setImageResource(R.mipmap.zhongjidaogou);
                        hysj.setText("中级编外导购");
                    }else if(level == 2){
                        ivVip.setVisibility(View.VISIBLE);
                        ivVip.setImageResource(R.mipmap.gaojidaogou);
                        hysj.setText("高级编外导购");
                    }else {
                        ivVip.setVisibility(View.VISIBLE);
                        ivVip.setImageResource(R.mipmap.hehuoren);
                        hysj.setText("合伙人");
                    }
                    //保存level
                    MyApp.getInstance().setLevel(level);
                    //SP保存的用户信息更新
                    LoginInfo loginInfo = NetHelper.getBeanForJson(LoginInfo.class, PrefsHelper.getLoginInfo());
                    loginInfo.setLevel(level);
                    PrefsHelper.setLoginInfo(loginInfo);

                    if (meInfoBean.getData().getMaid().equals("2")) {
                        maid.setText("已认证");
                    }

                    if (!meInfoBean.getMsgs().getMsg().equals("")) {
                        new AlertDialog.Builder(getActivity())
                                .setMessage(meInfoBean.getMsgs().getMsg())
                                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        setBlocking(meInfoBean.getMsgs().getAuth_id());
                                    }
                                }).show();
//                        ClearCacheDialog dlg = new ClearCacheDialog.Builder(getActivity())
//                                .setMessage(meInfoBean.getData().getMsgs().getMsgX())
//                                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
//                                    @Override
//                                    public void onClick(DialogInterface dialogInterface, int i) {
//                                        setBlocking(meInfoBean.getData().getMsgs().getAuth_id());
//                                        dialogInterface.dismiss();
//                                    }
//                                })
//                                .build();
//                        dlg.show();
                    }

                } else {
                    ToastUtil.show(getActivity(), meInfoBean.getMsg());
                }

            }
        });

    }

    /**
     * 不再提示
     *
     * @param auth_id
     */
    private void setBlocking(final String auth_id) {
        TreeMap<String, String> treeMap = new TreeMap<String, String>() {
            {
                put("auth_id", auth_id);
            }
        };
        NetHelper.get(APIServer.LOGIN_SETBLOCKING, treeMap, true, new NetHelper.HttpCallBack() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                /*请求得到的数据*/
                try {
                    JSONObject json = new JSONObject(s);
                    if (json.optString("code").equals("200")) {
                        ToastUtil.show(getActivity(), "该消息不会再提示");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(mcontext,"服务器异常",Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    /**
     * 压缩上传头像
     * @param picPath
     */
    public void setAva(String picPath) {
        //压缩图片后上传
        Luban.with(getActivity())
                .load(new File(picPath))  // 传人要压缩的图片列表
                .ignoreBy(10)             // 忽略不压缩图片的大小
                .setTargetDir(Environment.getExternalStorageDirectory().getPath())   // 设置压缩后文件存储位置
                .setCompressListener(new OnCompressListener() { //设置回调
                    @Override
                    public void onStart() {
                    }

                    @Override
                    public void onSuccess(final File file) {
                        OkGo.post(APIServer.AVATAR_URL)
                                .params("id",MyApp.getInstance().getUser_id())//用户id
                                .params("avatar",file)//图片
                                .execute(new StringCallback() {
                                    @Override
                                    public void onSuccess(String s, Call call, Response response) {
                                        try {
                                            JSONObject object = new JSONObject(s);
                                            if(object.getInt("code")==200){
                                                //请求成功
                                                Toast.makeText(getActivity(),"上传成功",Toast.LENGTH_SHORT).show();
                                                Glide.with(getActivity()).load(file).placeholder(R.mipmap.chanpin).into(mAvatar);
                                                String avatar_img = object.getString("avatar_img");
                                                MyApp.getInstance().setAvatar(avatar_img);
                                            }else {
                                                Toast.makeText(getActivity(),"上传失败",Toast.LENGTH_SHORT).show();
                                            }
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                            Toast.makeText(mcontext,"服务器异常",Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                });
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        Toast.makeText(getActivity(),"上传失败",Toast.LENGTH_SHORT).show();
                    }
                }).launch();    //启动压缩
    }

    /**
     * 点击事件
     * @param view
     */
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_avatar:  //上传头像
                ReleasePhotoDialog dialog = new ReleasePhotoDialog(getActivity(), 0, 1);
                dialog.show();
                break;
            case R.id.tv_hysj: //会员升级
                if (meInfoBean == null) {
                    return;
                }
                if (meInfoBean.getData() != null) {
                    startActivity(MemberDetailActivity.createIntent(getActivity(), meInfoBean.getData().getLevel()));
                }
                break;
            case R.id.iv_shezhi:
                overlay(SettingActivity.class);//设置
                break;
            case R.id.iv_message:
                overlay(MessageActivity.class);//消息
                break;
            case R.id.rl_ziliao:
                overlay(PersonalProfileActivity.class);//个人资料
                break;
            case R.id.rl_renzheng: //我的认证
                isCertificate();
                break;
            case R.id.rl_detail:
                overlay(MyOrderActivity.class);//我的订单
                break;
            case R.id.rl_money:
                MyWalletActivity.startAction(getActivity(), level); //我的钱包
                break;
            case R.id.rl_address:
                overlay(AddressActivity.class);//地址管理
                break;
        }
    }

    /**
     * 验证 我的认证
     */
    public void isCertificate() {
        showDialog();
        TreeMap<String, String> treeMap = new TreeMap<String, String>(){
            {
                put("user_id", MyApp.getInstance().getUser_id());//用户id
            }
        };
        NetHelper.get(APIServer.IS_PROFILE, treeMap, true, new NetHelper.HttpCallBack() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                JSONObject object;
                try {
                    object = new JSONObject(s);
                    if ( object.optString("code").equals("200")) {
                        //请求成功
                        startActivity(new Intent(getActivity(),MyCertificationActivity.class));//进入我的认证
                    } else {
                        ToastUtil.show(getActivity(), object.optString("msg"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(mcontext,"服务器异常",Toast.LENGTH_SHORT).show();
                }
                dismissDialog();
            }
        });
    }

    /**
     * 定义一个广播
     */
    public class MemberBroadcastReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            getServiceData();
        }
    }

    /**
     * 注册广播
     */
    private void registerBroadcastReceiver() {
        mBroadcastReceiver = new MemberBroadcastReceiver();
        IntentFilter mFilter = new IntentFilter();
        mFilter.addAction(ACTION_NAME);
        getContext().registerReceiver(mBroadcastReceiver, mFilter);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //解注册
        getContext().unregisterReceiver(mBroadcastReceiver);
    }
}
